import Vue from 'vue'
import Router from 'vue-router'
import Account from '@/service/account'
import Root from '@/app/Root'
import Layout from '@/app/Layout'
import notFound from './routes/notFound'
import home from './routes/home'
import users from './routes/users'
import login from './routes/login'
import logout from './routes/logout'
import iView from 'iview'
import roles from './routes/roles'
import events from './routes/events'
import images from './routes/images'
import account from './routes/account'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      component: Root,
      children: [
        {
          path: '/',
          component: Layout,
          children: [
            home,
            users,
            roles,
            events,
            images,
            account
          ],
          meta: {
            requiresAuth: true
          }
        },
        {
          path: 'license',
          component: resolve => require(['@/app/License'], resolve)
        },
        {
          path: 'register',
          component: resolve => require(['@/app/Register'], resolve)
        },
        {
          path: 'about',
          component: resolve => require(['@/app/About'], resolve)
        },
        {
          path: 'forgot',
          component: resolve => require(['@/app/ForgotPassword'], resolve)
        },
        {
          path: 'profile',
          component: resolve => require(['@/app/Account/Profile'], resolve)
        },
        {
          path: 'password',
          component: resolve => require(['@/app/Account/Password'], resolve)
        },
        {
          path: 'imageview/:id?',
          component: resolve => require(['@/app/ImageView'], resolve)
        },
        login,
        logout,
        notFound
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()

  if (to.matched.some(record => record.meta.requiresAuth)) {
    // if (to.path === '/') {
    //   next({
    //     path: 'official'
    //   })
    // } else
    if (!Account.isLoggedIn()) {
      next({
        path: 'login',
        query: {redirect: to.fullPath}
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

router.afterEach((to, from, next) => {
  iView.LoadingBar.finish()
})

export default router
